package com.gyyx.transfer.support;

import java.lang.reflect.Method;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.gyyx.transfer.service.DynamicDataSourceHolder;

/**
 * <p>
 * Title:DataSourceAspect
 * </p>
 * <p>
 * Description: 注解切面
 * </p>
 * 
 * @author Li Enbo
 * @date 2017年11月10日上午11:16:16
 */
@Aspect
@Component
public class DataSourceAspect {
	private static final Logger LOGGER = LoggerFactory.getLogger(DataSourceAspect.class);

	@Pointcut("@annotation(com.gyyx.transfer.support.DataSource)")
	public void pointCut() {
	}

	/**
	 * 前置通知 
	 * 
	 * @param joinPoint
	 * @throws Exception 
	 */
	@Before("pointCut()")
	public void doBefore(JoinPoint joinPoint) throws Exception {
		LOGGER.info("【前置通知开始】");
		DataSource giveController = giveController(joinPoint);
		LOGGER.info("【注解设置数据源{}】", giveController.value());
		if (StringUtils.isBlank(giveController.value())) {
			throw new IllegalArgumentException("【注解设置数据源没有捕获】");
		}
		DynamicDataSourceHolder.setDataSource(giveController.value());
	}

	/**
	 * 获得注解
	 * 
	 * @param joinPoint
	 * @return
	 * @throws Exception
	 */
	private static DataSource giveController(JoinPoint joinPoint) throws Exception {
		Signature signature = joinPoint.getSignature();
		MethodSignature methodSignature = (MethodSignature) signature;
		Method method = methodSignature.getMethod();

		if (method != null) {
			return method.getAnnotation(DataSource.class);
		}
		return null;
	}
}
